<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header('Access-Control-Allow-Origin:*');
header('Content-Type:application/json; charset=utf-8');
header('Access-Control-Allow-Methods:POST,GET,OPTIONS');
defined('BASEPATH') or exit('No direct script access allowed');
require 'JWT.php';
class ApiController extends CI_Controller {
	private $jwt;
	public $TOKEN="";
	private $response=array(
	  'code'=>1,
	  'msg'=>'success'
	);
	
	public function __construct(){
		parent::__construct();
		$this->jwt=new JWT();
		$headers=getallheaders();
	
		if (array_key_exists("Token", $headers)) {
			$this->TOKEN=$headers["Token"];
		} else {
			$this->TOKEN='';
		}	
	}
	public function index(){
	}
	
	//获取参数
	public function getKeys($params=[],$method='get'){
		$tips=[];
		$reqdata=[];
		foreach($params as $key=>$value){
			$pk=$value[0];
			$pr=$value[1]=='true';
			$pt=$value[2];
			$pd=$pr ? '':$value[3]; //非必要要，默认值为空
			$pv=$method=='get'? $this->input->get($pk): $this->input->post($pk);
			if($pr){ //必要参数
				if(is_null($pv) || $pv===''){
					array_push($tips,$pt);
				}
				$reqdata[$pk]=$pv;
			}else{
				if(is_null($pv) || $pv===''){  //没有传递，采用默认值
					$reqdata[$pk]=$pd;
				}else{
					$reqdata[$pk]=$pv;
				}
			}
		}
		//检测是否有必要参数未传递
		if($tips){
			header('Content-Type:text/html; charset=utf-8');
			echo (json_encode(array("code"=>0,"msg"=>"缺少必要参数:".implode(",",$tips)),JSON_UNESCAPED_UNICODE));
			exit();
		}
		return $reqdata;
	}
 	
	//写入某个字段值，没有则会自动添加
	public function WRITE($key, $value)
	{
		if (array_key_exists($key, $this->response)) {
			$this->response[$key]=$value;
		} else {
			$this->response[$key]=$value;
		}
	}
	
	public function RESPONSE()
	{
		echo json_encode($this->response, JSON_UNESCAPED_UNICODE);
	}
	
	
	/***********************JWT相关操作*******************************/
	public function createToken($data)
	{
	    //JWT生成算法
	    $this->jwt->setClaim($data);
	    return $this->jwt->createToken();
	}
	
	public function decodeToken($data){
		
		
	}

	public function verifyToken()
	{
		$token=$this->TOKEN;
		if(empty($token)){
			http_response_code(401);
			header('Content-Type:text/html; charset=utf-8');
			$this->WRITE("code",0);
			$this->WRITE("msg","登录状态或无权访问");
			$this->RESPONSE();
			return false;
		}else{
			$vtoken=$this->jwt->verifyToken($token);
			if (!$vtoken) {
				http_response_code(401);
				header('Content-Type:text/html; charset=utf-8');
				$this->WRITE("code",0);
				$this->WRITE("msg","登录状态或无权访问");
				$this->RESPONSE();
				return false;
			}
		}
		return $vtoken['claim'];
	}
}
